import { HttpService } from '@nestjs/axios';
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { JwtService } from '@nestjs/jwt';
import { InjectRepository } from '@nestjs/typeorm';
import { isEmpty } from 'lodash';
import Student from 'src/entities/student.entity';
import User from 'src/entities/user.entity';
import { RedisService } from 'src/shared/redis/redis.service';
import { Repository } from 'typeorm';
import { WeChatDto } from './auth.dto';
import { ApiException } from 'src/core/exceptions/api.exception';
import { compareSync } from 'bcryptjs';
import { USER_TOKEN } from 'src/core/contants';
import Admin from 'src/entities/admin/admin.entity';

@Injectable()
export class AuthService {
  constructor(
    @InjectRepository(User) private userRepository: Repository<User>,
    @InjectRepository(Student) private studentRepository: Repository<Student>,
    private httpService: HttpService,
    private configService: ConfigService,
    private redisService: RedisService,
    private jwtService: JwtService,
  ) {}

  // 企业登录
  async company(weChatDto: WeChatDto) {
    const { username, password } = weChatDto;
    const redis = this.redisService.getRedis();

    const user = await this.userRepository.findOne({ where: { username } });
    if (isEmpty(user)) {
      throw new ApiException(10007);
    }
    if (!compareSync(password, user.password)) {
      throw new ApiException(10007);
    }
    // 生成token并存储
    const token = this.jwtService.sign({ uid: user.id, role: user.role });
    await redis.set(`${USER_TOKEN + user.id}`, token, 'EX', 60 * 60 * 24);
    return { token };
  }

  // 退出登录
  async logout(userId: string) {
    const redis = this.redisService.getRedis();
    await redis.del(`${USER_TOKEN + userId}`);
    return { message: 'logout success' };
  }

  // 学生登录
  async student(weChatDto: WeChatDto) {
    const { username, password } = weChatDto;
    const redis = this.redisService.getRedis();

    const user = await this.userRepository.findOne({ where: { username } });
    if (isEmpty(user)) {
      throw new ApiException(10007);
    } else if (!compareSync(password, user.password)) {
      throw new ApiException(10007);
    }

    // 生成token并存储
    const token = this.jwtService.sign({ uid: user.id, role: user.role });
    await redis.set(`${USER_TOKEN + user.id}`, token, 'EX', 60 * 60 * 24);
    return { token };
  }

  // 后台管理登录
  async login(user: Admin) {
    // 生成token并存储
    const redis = this.redisService.getRedis();
    const token = this.jwtService.sign({
      uid: user.id,
      role: user.username,
    });

    await redis.set(`${USER_TOKEN + user.id}`, token, 'EX', 60 * 60 * 24);
    return { token };
  }

  // 获取微信小程序登录信息
  wechatInfo() {
    const appid = this.configService.get<string>('WX_APPID');
    const secret = this.configService.get<string>('WX_SECRET');
    const grant_type = this.configService.get<string>('WX_GRANT_TYPE');
    return { appid, secret, grant_type };
  }
}
